"""Select SQLite Table

.. helpdoc::
Basic sqlite statement evaluator.  This widget allows one to execute specific sql statements on a recieved database and generate an sql view.  Essentially always running CREATE VIEW widgetname AS statement.
"""


"""<widgetXML>
    <name>
        Select SQLite Table
    </name>
    <icon>
        readfile.png
    </icon>
    <summary>
        Selects a table from an SQLite database and sends that as a table signal.
    </summary>
    <tags>
        <tag priority="50">
            SQLite
        </tag>
    </tags>
    <author>
        <authorname>Kyle R. Covington</authorname>
        <authorcontact>kyle@red-r.org</authorcontact>
    </author>
    </widgetXML>
"""


from OWRpy import *
import redRGUI
import sqlite3 
import re, os, redR
class selectTable(OWRpy):
    def __init__(self, **kwargs):

        OWRpy.__init__(self, **kwargs)
        self.database = None
        """.. rrsignals::"""
        self.inputs.addInput("Database", "Database", signals.RedRSQLite.SQLiteDatabase, self.processDatabase)
        
        """.. rrsignals::"""
        self.outputs.addOutput("SQLite Data Table", "SQLite Data Table", signals.RedRSQLite.SQLiteTable)
        
        #### GUI ####
        
        """.. rrgui::"""
        self.tableNames = redRGUI.base.listBox(self.controlArea, label = 'Available Tables:', toolTip = 'A list of available tables that can be selected.  The selected table will be sent into the schema.', callback = self.sendTable)
        
    def processDatabase(self, data):
        if data:
            self.database = data
            self.setNames()
        else:
            self.database = None
    
    def setNames(self):
        if self.database == None:
            return
        conn = sqlite3.connect(self.database.getDatabase())
        c = conn.cursor()
        tables = [t[0] for t in c.execute('SELECT name FROM sqlite_master WHERE type = "table" OR type = "view"').fetchall()]
        c.close()
        self.tableNames.update(tables)
        
    def sendTable(self):
        if self.database == None:
            return
        newData = signals.RedRSQLite.SQLiteTable(self, data = self.tableNames.selectedIds()[0], database = self.database.getData())
        self.rSend("SQLite Data Table", newData)